//
//  NSData+extension.swift
//  XLProject
//
//  Created by xinglian on 2022/2/25.
//

import UIKit
import CommonCrypto

@objc public extension NSData
{
    var md5: String
    {
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(self.bytes, CC_LONG(self.length), result)
        let hash = NSMutableString()
        for i in 0..<CC_MD5_DIGEST_LENGTH {
            hash.appendFormat("%02x", result[Int(i)])
        }
        result.deallocate()
        return hash as String
    }
    
    var SHA256:String
    {
        let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_SHA256(self.bytes, CC_LONG(self.length), result)
        let hash = NSMutableString()
        for i in 0..<CC_SHA256_DIGEST_LENGTH {
            hash.appendFormat("%02x", result[Int(i)])
        }
        result.deallocate()
        return hash as String
    }
}

public extension Data{
    var uint8 : [UInt8]{
        return [UInt8](self)
    }
    var hex : String{
        return self.uint8.map { String(format: "%02X", $0) }.joined(separator: ", ")
    }
}
